package com.rescue.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rescue.constant.MessageConstant;
import com.rescue.context.BaseContext;
import com.rescue.exception.BaseException;
import com.rescue.forum.dto.AcceptRescueDTO;
import com.rescue.forum.dto.CommonRescueDTO;
import com.rescue.forum.dto.FastRescueDTO;
import com.rescue.forum.dto.RecordPageQueryDTO;
import com.rescue.forum.entity.RescueFile;
import com.rescue.forum.entity.RescueRecord;
import com.rescue.forum.vo.RecordPageQueryVO;
import com.rescue.forum.vo.UserDataVO;
import com.rescue.mapper.*;
import com.rescue.result.PageResult;
import com.rescue.service.RescueRecordService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class RescueRecordServiceImpl implements RescueRecordService {
    @Autowired
    private RescueRecordMapper rescueRecordMapper;
    @Autowired
    private RescueManMapper rescueManMapper;
    @Autowired
    private RescueFileMapper rescueFileMapper;
    @Autowired
    private UserMessageMapper userMessageMapper;
    @Autowired
    private LikeRecordMapper likeRecordMapper;
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private CommentMapper commentMapper;

    /**
     * 请求快速救援
     *
     * @param fastRescueDTO
     */
    public void fastRescue(FastRescueDTO fastRescueDTO) {
        //新增救援记录
        RescueRecord rescueRecord = new RescueRecord();
        BeanUtils.copyProperties(fastRescueDTO, rescueRecord);
        rescueRecord.setRescueStatus(0);
        rescueRecord.setRescueType(1);
        rescueRecord.setSendTime(LocalDateTime.now());
        rescueRecordMapper.save(rescueRecord);
    }

    /**
     * 请求普通救援
     *
     * @param commonRescueDTO
     */
    @Transactional
    public void commonRescue(CommonRescueDTO commonRescueDTO) {
        RescueRecord rescueRecord = new RescueRecord();
        BeanUtils.copyProperties(commonRescueDTO, rescueRecord);
        rescueRecord.setRescueType(0);
        rescueRecord.setRescueStatus(0);
        rescueRecord.setSendTime(LocalDateTime.now());
        rescueRecordMapper.save(rescueRecord);
        //保存文件
        List<RescueFile> fileList = new ArrayList<>();
        if (commonRescueDTO.getImgS() != null) {
            List<String> list = JSONObject.parseArray(commonRescueDTO.getImgS(), String.class);
            list.forEach(s -> fileList.add(RescueFile.builder()
                    .status(0)
                    .userId(commonRescueDTO.getUserId())
                    .rescueRecordId(rescueRecord.getRescueRecordId())
                    .type(0)
                    .filePath(s).build()));
        }
        if (commonRescueDTO.getAudioS() != null) {
            fileList.add(RescueFile.builder()
                    .status(0)
                    .userId(commonRescueDTO.getUserId())
                    .rescueRecordId(rescueRecord.getRescueRecordId())
                    .type(1)
                    .filePath(commonRescueDTO.getAudioS()).build());
        }
        if (commonRescueDTO.getVideoS() != null) {
            fileList.add(RescueFile.builder()
                    .status(0)
                    .userId(commonRescueDTO.getUserId())
                    .rescueRecordId(rescueRecord.getRescueRecordId())
                    .type(2)
                    .filePath(commonRescueDTO.getVideoS()).build());
        }
        rescueFileMapper.saveBatch(fileList);
    }

    /**
     * 分页查询救援记录
     *
     * @param recordPageQueryDTO
     * @return
     */
    public PageResult PageQuery(RecordPageQueryDTO recordPageQueryDTO) {

        PageHelper.startPage(recordPageQueryDTO.getPage(), recordPageQueryDTO.getPageSize());
        Page<RecordPageQueryVO> list = rescueRecordMapper.getPage(recordPageQueryDTO);
        //添加文件
        list.forEach(item -> {
            //查询图片
            List<String> list1 = rescueFileMapper.getByRecordId(item.getRescueRecordId(), 0);
            item.setImgS(list1);
            List<String> list2 = rescueFileMapper.getByRecordId(item.getRescueRecordId(), 1);
            item.setAudioS((list2 != null && list2.size() > 0) ? list2.get(0) : null);
            List<String> list3 = rescueFileMapper.getByRecordId(item.getRescueRecordId(), 2);
            item.setVideoS((list3 != null && list3.size() > 0) ? list3.get(0) : null);
        });

        return new PageResult(list.getTotal(), list.getResult());
    }


    /**
     * 接收救援
     *
     * @param acceptRescueDTO
     */
    @Transactional
    public void     acceptRescue(AcceptRescueDTO acceptRescueDTO) {
        //如果当前用户有要未完成的救援需先完成
        Integer rescueUserId = acceptRescueDTO.getRescueUserId();
        Page<RecordPageQueryVO> page = rescueRecordMapper.getPage(RecordPageQueryDTO.builder()
                .rescueUserId(rescueUserId)
                .rescueStatus(1).build());
        if (page.getTotal() != 0) {
            throw new BaseException(MessageConstant.PLEASE_COMPLETE_THE_CURRENT_RESCUE_FIRST);
        }
        //接受救援
        RescueRecord rescueRecord = new RescueRecord();
        BeanUtils.copyProperties(acceptRescueDTO, rescueRecord);
        rescueRecord.setRescueStatus(1);
        rescueRecordMapper.update(rescueRecord);

    }

    /**
     * 完成救援
     *
     * @param rescueRecordId
     */
    public void completeRescue(Integer rescueRecordId) {
        RescueRecord rescueRecord = rescueRecordMapper.getById(rescueRecordId);
        //只有救援者能完成自己的救援
        if (!Objects.equals(rescueRecord.getRescueUserId(), BaseContext.getCurrentId())) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        rescueRecordMapper.update(RescueRecord.builder().rescueRecordId(rescueRecordId)
                .completionTime(LocalDateTime.now())
                .rescueStatus(2)
                .build());
    }

    /**
     * 取消救援
     *
     * @param rescueRecordId
     */
    public void callOffRescue(Integer rescueRecordId) {
        RescueRecord rescueRecord = rescueRecordMapper.getById(rescueRecordId);
        //只有救援者能完成自己的救援
        if (!Objects.equals(rescueRecord.getUserId(), BaseContext.getCurrentId())) {
            throw new BaseException(MessageConstant.UNKNOWN_ERROR);
        }
        rescueRecordMapper.update(RescueRecord.builder().rescueRecordId(rescueRecordId)
                .rescueStatus(3)
                .build());
    }

    /**
     * @param userId
     * @return
     */
    public UserDataVO getUserData(Integer userId) {
        return UserDataVO.builder().rescueTimes(rescueRecordMapper.getRTimeById(userId))
                .acceptRescueTimes(rescueRecordMapper.getBRTimeById(userId))
                .likeTimes(likeRecordMapper.getBCLikeTimesById(userId) + likeRecordMapper.getBALikeTimesById(userId))
                .numberOfArticles(articleMapper.getNumById(userId))
                .numberOfComments(commentMapper.getNumById(userId)).build();


    }
}
